package com.lgc.service.room

import android.content.Context
import androidx.annotation.Keep
import androidx.lifecycle.LiveData
import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Delete
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.Update

/**
 * 定义数据库 room
 * 库名:tb_edu_user
 */
//3,创建database
@Database(entities = [EduUserInfo::class], version = 1, exportSchema = false)
abstract class EduUserDataBase:RoomDatabase(){
    abstract val userDao:EduUserDao
    companion object{
        @Volatile
        private var instance:EduUserDataBase?=null
        private const val EDU_DB_NAME="tb_edu_user"
        @JvmStatic
        fun getInstance(context:Context):EduUserDataBase{
            return instance?: synchronized(EduUserDataBase::class){
                Room.databaseBuilder(context.applicationContext,EduUserDataBase::class.java,EDU_DB_NAME).build().apply {
                    instance=this
                }
            }
        }
    }
}

//1,Entity的定义
@Entity(tableName = "tb_edu_user")
data class EduUserInfo(
    @PrimaryKey
    val id:Int,//主键
    val course_permission:Boolean,//是否拥有学习卡权限
    val token:String,//token
    @Embedded
    val user:User?//用户信息
){
    @Keep
    data class User(
        @ColumnInfo(name = "edu_user_id")
        val id:Int,//用户id
        val logo_url:String,//用户头像地址
        val req_time:String,//用户注册时间
        val username:String//用户名
    )
}

//2 Dao层定义
@Dao
interface EduUserDao{
   @Insert(onConflict = OnConflictStrategy.REPLACE)//数据重复时,替换
    fun insertUser(eduUserInfo: EduUserInfo)

    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun updateUser(eduUserInfo: EduUserInfo)

    @Delete
    fun deleteUser(eduUserInfo: EduUserInfo)

    //=,in ,like
    @Query("select * from tb_edu_user where id=:id")
    fun queryLiveUser(id:Int=0):LiveData<EduUserInfo>

    @Query("select * from tb_edu_user where id=:id")
    fun queryUser(id:Int=0):EduUserInfo?
}
